package com.huawei.jenkins.iam;


import com.google.common.base.Preconditions;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.csms.v1.CsmsClient;
import com.huaweicloud.sdk.csms.v1.model.ShowSecretVersionRequest;
import com.huaweicloud.sdk.csms.v1.model.ShowSecretVersionResponse;
import com.huaweicloud.sdk.csms.v1.region.CsmsRegion;
import hudson.model.TaskListener;
import org.apache.commons.lang.StringUtils;

import java.io.Serializable;

public class secretService implements Serializable {
    private static final long serialVersionUID = 1;


    public static String getCredentials(TaskListener listener, CustomInput customInput){

        inputValidate(customInput);

        ICredential auth = new BasicCredentials()
                .withAk(customInput.getAccessKey())
                .withSk(customInput.getSecretKey());

        CsmsClient csmsClient = CsmsClient.newBuilder()
                .withCredential(auth)
                .withRegion(CsmsRegion.valueOf(customInput.getRegion()))
                .build();

        String secretString ="";
        try {
            ShowSecretVersionResponse latestVersionValue = csmsClient.showSecretVersion(new ShowSecretVersionRequest().withSecretName(customInput.getSecretName()).withVersionId(customInput.getVersionId() == null ? "latest" : customInput.getVersionId()));
            secretString = latestVersionValue.getVersion().getSecretString();
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            listener.getLogger().println("ErrorMsg：" + e.getErrorMsg());
        }
      return  secretString;
    }



    private static void inputValidate(CustomInput customInput) {
        final String secretName = customInput.getSecretName();
        final String region = customInput.getRegion();
        final String sk = customInput.getSecretKey();
        final String ak = customInput.getAccessKey();
        Preconditions.checkArgument(StringUtils.isNotBlank(secretName), "ObsPath can not be blank");
        Preconditions.checkArgument(StringUtils.isNotBlank(region), "region can not be blank");
        Preconditions.checkArgument(StringUtils.isNotBlank(ak) && StringUtils.isNotBlank(sk), "Ak, Sk can not be blank");
    }


}
